from ipaddress import ip_address

path = "E:\\python\\ex\\w4501\\练习\\works.txt"


def home_work():
    try:
        with open(path, "r", encoding="utf-8") as file:
            x = file.read()
            dic = eval(x)
    except ValueError :
        dic = {}

    while True:
        work = input("请输入家务名称：").strip()
        if work == '':
            break
        if work in dic:
            dic[work] += 1
            print(f"{work} 的次数已增加到 {dic[work]}。")
        else:
            dic[work] = 1
            print(f"{work} 已添加到字典中。")

    print("\n当前家务字典：")
    for task, count in dic.items():
        print(f"{task}: {count}")

    y = str(dic)
    try:
        with open(path, "w", encoding="utf-8") as f:
            f.write(y)
        print("家务字典已保存到文件中。")
    except Exception as e:
        print(f"写入文件时发生错误：{e}")


if __name__ == '__main__':
    home_work()